//
//  HomeTableViewController.swift
//  01-SLWeibo
//
//  Created by 李博 on 15/6/23.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import SVProgressHUD

///转发微博 Cell
let LBStatusForwardCellIdentifier = "LBStatusForwardCellIdentifier"
///原创微博 Cell
let LBStatusNormalCellIdentifier = "LBStatusNormalCellIdentifier"

class HomeTableViewController: BaseTableViewController, StatusCellDelegate {

    var statusList: [Status]? {
        didSet {
            //刷新表格
            tableView.reloadData()
            
        }
    }
    
    ///定义缓存行高
    lazy var rowHeightCache = [Int: CGFloat]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        visitorView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        if !userLogon {
            return
        }
        
        setupNavigationBar()
        prepareTableView()
        prepareRefresh()
        
        
    }
    private func prepareRefresh() {
        
        refreshControl = LBRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        //加载数据
        loadData()
    }
    
    ///准备 tableView
    private func prepareTableView() {
        
        // 注册可重用 cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: LBStatusForwardCellIdentifier)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: LBStatusNormalCellIdentifier)
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        // 清空缓存，提示：NSCache 不能清空
        rowHeightCache.removeAll()
    }

    ///加载微博数据
    func loadData() {
        //开始刷新不会触发监听方法，会显示刷新控件
        refreshControl?.beginRefreshing()
        
        //下拉刷新的代号，取到数值中的第一条数据
        var since_id = statusList?.first?.id ?? 0
        var max_id = 0
        if pullRefreshFlag {
            since_id = 0
            max_id = statusList?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) {(statuses, error) -> () in
            
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("你的网速不给力。。。")
                return
            }
            if statuses == nil {
                print("没有数据！！！")
                return
            }
            
            print("加载了 \(statuses?.count)")

            if since_id > 0 {
                //拉下刷新
                self.statusList = statuses! + self.statusList!
            }else if max_id > 0{
                //上拉刷新
                self.statusList = self.statusList! + statuses!
                self.pullRefreshFlag = false
            }else {
                //初始化刷新
                self.statusList = statuses
            }
        }
    }
    //MARK: -- 数据源 --
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusList?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //1. 取得数据模型
        let status = statusList![indexPath.row]
        // ------此方法必须注册可重用cell，如果不注册，会崩溃------
        //2. 取得标示符
        let ID = StatusCell.cellIdentifier(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        
        //设置代理
        cell.photoDelegate = self
        
        //3. 设置Cell
        cell.status = status
        
        //4. 判断到倒数第三行时，加载新数据
        if indexPath.row == statusList!.count - 3 {
            pullRefreshFlag = true
            loadData()
        }
        
        return cell
    }
    
    ///cell行高代理
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //1.获取对象模型
        let status = statusList![indexPath.row]
        
        //判断是否缓存了行高，如果有直接返回
        if rowHeightCache[status.id] != nil {
            return rowHeightCache[status.id]!
        }
        //获取Cell
        let ID = StatusCell.cellIdentifier(status)
        
        var cls: AnyClass = StatusNormalCell.self
        if ID == LBStatusForwardCellIdentifier {
            cls = StatusForwardCell.self
        }
        let cell = cls.new() as! StatusCell
        
        //返回行高
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
        
    }
    //MARK: -- Cell的代理 --
    func statusCellDidSelectPhoto(cell: StatusCell, photoIndex: Int) {
        if cell.status?.largePicURLs == nil {
            return
        }
        
        let vc = PhotoBrowserViewController(urls: cell.status!.largePicURLs!, index: photoIndex)
        
        //准备转场的素材
        presentedImageView.sd_setImageWithURL(cell.status!.largePicURLs![photoIndex])
        presentedImageView.frame = cell.pictureCellScreenFrame(photoIndex)
        
        //目标位置
        presentedFrame = cell.fullScreenFrame(photoIndex)
        //记录当前行
        selectedStatusCell = cell
        
        
        //设置转场代理
        vc.transitioningDelegate = self
        //设置转场样式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
        
    }
    ///临时的图片视图
    private lazy var presentedImageView = UIImageView()
    ///目标位置
    private var presentedFrame = CGRectZero
    ///用户选中的表格行
    private var selectedStatusCell: StatusCell?
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //开启动画
        visitorView?.startAnimation()
    }
    
    
    ///显示二维码界面
    func showQRCode() {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    ///设置导航条
    private func setupNavigationBar() {
        //判断用户是否登录
        if sharedUserAccount == nil {
            return
        }
        
        //设置按钮
        let leftBtn = UIButton(frame: CGRectMake(0, 0, 30, 30))
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        
        let rightBtn = UIButton(frame: CGRectMake(0, 0, 30, 30))
        rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        
        let btn = navigationItem.rightBarButtonItem?.customView as! UIButton
        btn.addTarget(self, action: "showQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        
        //设置标题
        let name = sharedUserAccount!.name!
        let titleBtn = HomeTitleButton(frame: CGRectMake(0, 0, 120, 30))
        titleBtn.setTitle("\(name)", forState: UIControlState.Normal)
        titleBtn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        titleBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        
        titleBtn.addTarget(self, action: "titleBtnClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleBtn
        
    }
    /// 动画转场代理
    let popoverAninmator = PopoverAnimator()
    
    //标题按钮点击
    func titleBtnClicked() {
        
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        //设置转场代理
        vc.transitioningDelegate = popoverAninmator
        
        //设置视图的展现大小
        let x = (view.bounds.width - 200) * 0.5
        popoverAninmator.presentFrame = CGRectMake(x, 56, 200, 300)
        //3.设置转场动画
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    ///上拉刷新标记
    private var pullRefreshFlag = false
    
    ///转场标记
    private var isPresented = false

}

extension HomeTableViewController: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    //返回提供转场 Modal 动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    //一旦实现，需要程序员提供动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        //1. 获取目标视图
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        if targetView == nil {
            return
        }
        
        if isPresented {
            
            //2. 添加
            transitionContext.containerView()?.addSubview(targetView!)
            targetView?.alpha = 0.0
            //2.1 添加临时的图片视图
            transitionContext.containerView()?.addSubview(presentedImageView)
            
            //3. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                self.presentedImageView.frame = self.presentedFrame
                
                }, completion: { (_) -> Void in
                    
                    //删除临时图片视图
                    self.presentedImageView.removeFromSuperview()
                    
                    targetView?.alpha = 1.0
                    //动画完成
                    transitionContext.completeTransition(true)
            })
            
        }else {
            // 获取要缩放图片
            let targetVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserViewController
            let iv = targetVC.currentImageView()
            //iv.contentMode = UIViewContentMode.ScaleAspectFill
            
            //形变叠加
            iv.transform = CGAffineTransformScale(iv.transform, targetView!.transform.a, targetView!.transform.a)
            //设置图像视图的中心点
            iv.center = targetView!.center
            
            //1. 添加到容器视图
            transitionContext.containerView()?.addSubview(iv)
            //2. 将目标视图直接删除
            targetView?.removeFromSuperview()
            //3. 恢复的位置
            let targetFrame = selectedStatusCell!.pictureCellScreenFrame(targetVC.currentImageIndex())
            
            
            //4. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                iv.frame = targetFrame
                
                }, completion: { (_) -> Void in
                    
                    iv.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
            
        }
    }
}
